package org.xteam.box2text.old;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.xteam.box2text.Frame;
import org.xteam.box2text.Point;
import org.xteam.box2text.TextStruct;

public class VOperator extends Operator implements IPlaceableBox {
	
	public VOperator(Box...boxes) {
		super(boxes);
	}
	
	public VOperator(int vs, Box...boxes) {
		super(boxes);
		options.put("vs", vs);
	}

	public VOperator(int vs, List<Box> arguments) {
		super(arguments);
		options.put("vs", vs);
	}
	
	public VOperator(Map<String, Integer> options, List<Box> arguments) {
		super(options, arguments);
	}

	public Box removeVertical(boolean removeRow) {
		return new HOperator(options, removeVertical(arguments, removeRow));
	}

	public int width(Frame frame) {
		int max = 0;
		for (Box arg : arguments) {
			int w = ((IPlaceableBox)arg).width(frame);
			if (w > max)
				max = w;
		}
		return max;
	}

	public TextStruct place(Frame frame, TextStruct textStruct, int context) {
		if (isEmpty())
			return textStruct;
		if (size() == 1) {
			return ((IPlaceableBox)arguments.get(0)).place(frame, textStruct, OperatorKinds.V);
		}
		int Vs = frame.getVs(options());
		Frame Frame2 = frame.setLeftMargin(frame.x());
		return vplace(arguments, Vs, Frame2, textStruct);
	}
	
	protected static TextStruct vplace(List<Box> boxes, int Vs, Frame f, TextStruct textStruct) {
		for (Box b : boxes) {
			textStruct = ((IPlaceableBox)b).place(f, textStruct, OperatorKinds.V);
			f = f.vsep(textStruct.point(), Vs);
		}
		return textStruct;
	}

	public Point length(Frame frame, int context) {
		if (isEmpty()) {
			return new Point(0,0);
		}
		return vlength(arguments, frame);
	}

	private Point vlength(List<Box> arguments, Frame frame) {
		Point bp = null;
		for (Box arg : arguments) {
			if (bp == null) {
				bp = ((IPlaceableBox)arg).length(frame, OperatorKinds.V);
			} else {
				bp = v(bp, ((IPlaceableBox)arg).length(frame, OperatorKinds.V));
			}
		}
		return bp;
	}
	
	private static Point v(Point p1, Point p2) {
		if (p2.isZero())
			return p1;
		if (p1.isZero())
			return p2;
		return new Point(p2.width(), p1.height() + 1 + p2.height());
	}
	
	@Override
	public List<Box> normalizeGroups(boolean splice) {
		return Arrays.asList(new Box[] { new VOperator(options, normalizeChildren(true)) });
	}

}
